package com.weichen.studentgameexchange.message.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.weichen.studentgameexchange.common.common.Result;
import com.weichen.studentgameexchange.common.common.StrIsNumOrChinese;
import com.weichen.studentgameexchange.message.entity.Message;
import com.weichen.studentgameexchange.message.entity.MessageType;
import com.weichen.studentgameexchange.message.dao.MessageTypeMapper;
import com.weichen.studentgameexchange.message.service.IMessageTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 惟尘
 * @since 2025-02-08
 */
@Service
public class MessageTypeServiceImpl extends ServiceImpl<MessageTypeMapper, MessageType> implements IMessageTypeService {

    @Autowired
    MessageTypeMapper messageTypeMapper;

    @Override
    public Result adminPage(String keyword, Integer page, Integer size) {
        Page<MessageType> messageTypePage = new Page<>(page,size);
        LambdaQueryWrapper<MessageType> messageTypeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        messageTypeLambdaQueryWrapper.orderByDesc(MessageType::getTypeId);
        if (!StrUtil.isBlankIfStr(keyword)){
            Object o = StrIsNumOrChinese.strIsNumOrChinese(keyword);
            if (o instanceof Long)
                messageTypeLambdaQueryWrapper.eq(MessageType::getTypeId,o);
            else if (o instanceof Result)
                return Result.error("搜索输入的关键字不正确！");
            else if (o instanceof String)
                messageTypeLambdaQueryWrapper.like(MessageType::getTypeName,o);
        }
        Page<MessageType> selectPage = messageTypeMapper.selectPage(messageTypePage, messageTypeLambdaQueryWrapper);
        return Result.success(selectPage);
    }

    /**
     * 删除单个消息类型
     * @param typeId
     * @return
     */
    @Override
    public Result adminDeleteOne(Long typeId) {
        messageTypeMapper.deleteById(typeId);
        Message message = Db.lambdaQuery(Message.class)
                .eq(Message::getTypeId, typeId)
                .one();
        if (!StrUtil.isBlankIfStr(message)){
            Db.lambdaUpdate(Message.class)
                    .eq(Message::getTypeId,typeId)
                    .set(Message::getTypeId,0);
        }
        return Result.success();
    }
}
